package com.dkt.android.mvp.presenter

import com.dkt.android.api.UserApiService
import com.dkt.android.base.BaseCallSubscriber
import com.dkt.android.base.BasePresenterImpl
import com.dkt.android.base.BaseRsps
import com.dkt.android.core.RouterHub
import com.dkt.android.mvp.contract.ListContract
import com.dkt.android.mvp.model.IndexShopBean
import retrofit2.Response

/**
 * @author: jcm
 * @email: jiangcm@aplus-it.cn
 * @createTime: 20-6-3
 */
class ListPresenter : BasePresenterImpl(), ListContract.Presenter{

    val listSon = mutableListOf<IndexShopBean>()

    override fun refreshList(view: ListContract.View, isAdd: Boolean, page: String, name: String) {
        handler.createNetWork<Response<BaseRsps<List<IndexShopBean>>>>(page)
                ?.apply {
                    observable = UserApiService.itemList(page,name)
                    disposable = object : BaseCallSubscriber<List<IndexShopBean>>() {
                        override fun onSuccess(baseRsps: BaseRsps<List<IndexShopBean>>?) {
                            val b = baseRsps?.data
                            if (!isAdd) {
                                listSon.clear()
                            }
                            if (b?.isNotEmpty() == true) {
                                listSon.addAll(b)
                            } else {
                                view.equalToFunc {
                                    it.back()
                                }
                            }

                            view.equalToFunc {
                                it.refreshView(listSon)
                            }
                        }

                        override fun onError(t: Throwable) {
                            super.onError(t)
                            view.equalToFunc {
                                it.err()
                            }
                        }

                        override fun onEnd() {
                            super.onEnd()
                            afterEnd?.invoke()
                        }
                    }

                    afterEnd = {
                        view.equalToFunc {
                            it.refreshOnEnd(isAdd)
                        }
                    }
                }?.start()
    }
}